<template>
  <el-dialog v-el-drag-dialog :title="!form.userId?'新建用户':'编辑用户'" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-form ref="userForm" :model="form" :rules="rules" label-width="120px" :disabled="!hasLoaded">
      <el-form-item hidden>
        <el-input v-model="form.userId" hidden />
      </el-form-item>
      <el-form-item prop="deptId" hidden>
        <el-input v-model="form.deptId" hidden />
      </el-form-item>
      <el-form-item prop="avatar" hidden>
        <el-input v-model="form.avatar" hidden />
      </el-form-item>
      <el-form-item prop="roleIds" hidden>
        <el-input v-model="form.roleIds" hidden />
      </el-form-item>

      <el-card header="基本信息">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptName">
          <el-input v-model="form.deptName" readonly>
            <el-button v-if="hasLoaded" slot="append" icon="el-icon-search" @click="selectDept" />
          </el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input v-model="form.loginName" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="form.status">
            <el-option
              v-for="item in optionOfStatus"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="岗位" prop="postSelect">
          <el-select v-model="form.postSelect" clearable filterable multiple @change="changePost">
            <el-option
              v-for="item in optionOfPost"
              :key="'user_post_' + item.id"
              :label="item.text"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender">
            <el-option
              v-for="item in optionOfGender"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-card>
      <el-divider />
      <el-card header="角色信息">
        <el-tag
          v-for="(item, index) in form.roleNames"
          :key="'role_name_' + index"
          effect="plain"
          style="margin-right:5px;"
        >
          {{ item }}
        </el-tag>
        <el-button v-if="hasLoaded" class="fr" icon="el-icon-search" @click="selectRole">选 择</el-button>
      </el-card>
      <el-divider />
      <el-card header="其它信息">
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-card>
    </el-form>

    <dept-tree-dialog v-if="openDeptDialog" ref="deptDialog" @confirmDialog="setDept" />
    <role-tree-dialog v-if="openRoleDialog" ref="roleDialog" :single="false" @confirmDialog="setRole" />
    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { userLoad, userSave } from '@/api/system/user'
import { postSelectData } from '@/api/system/post'
import { validUserName, validMobile } from '@/utils/validate'
import DeptTreeDialog from '@/views/system/dept/tree/dialog'
import RoleTreeDialog from '@/views/system/role/tree/dialog'
import elDragDialog from '@/directive/el-drag-dialog'

export default {
  name: 'UserFormDialog',
  components: {
    DeptTreeDialog,
    RoleTreeDialog
  },
  directives: {
    elDragDialog
  },
  data() {
    const validateUniq = (rule, value, callback) => {
      if (value === undefined || value === '') {
        // rule.message = '该项不能为空'
        // return callback(new Error(rule.message))
        return callback()
      }

      const param = rule.param.replaceParam
      rule.param[param] = value
      rule.param.userId = this.form.userId
      this.$http.get(rule.url, {
        params: rule.param
      }).then(response => {
        if (response.valid) {
          callback()
        } else {
          callback(new Error(rule.message))
        }
      }).catch(() => {
        callback()
      })
    }

    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        userId: undefined,
        deptId: undefined,
        avatar: undefined,
        roleIds: '',
        userName: '',
        deptName: '',
        loginName: '',
        status: '0',
        gender: '',
        email: '',
        mobile: '',
        birthday: undefined,
        postIds: '',
        postSelect: [],
        roleNames: [],
        remark: ''
      },
      optionOfPost: [],
      optionOfStatus: [],
      optionOfGender: [],
      rules: {
        userName: [{ required: true, trigger: 'blur', message: '用户名称不能为空' }],
        deptName: [{ required: true, trigger: 'blur', message: '请选择所属部门' }],
        loginName: [{
          required: true,
          trigger: 'blur',
          param: {
            loginName: 'loginName'
          },
          validator: validateUniq,
          url: `${process.env.VUE_APP_MODULE_ADMIN_API}/public/user/unique`,
          message: '已存在登录账号'
        }, {
          trigger: 'blur',
          validator: validUserName
        }],
        email: [
          // { required: true, trigger: 'blur', message: '邮箱不能为空' },
          { type: 'email', trigger: 'blur', message: '邮箱格式不正确' },
          {
            trigger: 'blur',
            param: {
              email: 'email'
            },
            validator: validateUniq,
            url: `${process.env.VUE_APP_MODULE_ADMIN_API}/public/user/unique`,
            message: '已存在该邮箱'
          }
        ],
        mobile: [
          // { required: false, trigger: 'blur', message: '手机不能为空' },
          { validator: validMobile, trigger: 'blur', message: '手机格式不正确' },
          {
            trigger: 'blur',
            param: {
              mobile: 'mobile'
            },
            validator: validateUniq,
            url: `${process.env.VUE_APP_MODULE_ADMIN_API}/public/user/unique`,
            message: '已存在该手机号'
          }]
      },
      openDeptDialog: false,
      openRoleDialog: false
    }
  },
  methods: {
    init(userId, deptId) {
      this.hasLoaded = false
      this.form.roleNames = []
      this.form.userId = userId || null
      this.visible = true
      this.$nextTick(() => {
        this.$refs.userForm.resetFields()
        if (this.form.userId) {
          this.loadForm(userId, deptId)
        } else {
          this.form.deptId = deptId || null
          this.hasLoaded = this.$perm.hasPermissionOr(['system:user:edit'])
        }
        this.getDictData()
      })
    },
    loadForm(userId, deptId) {
      userLoad({
        'id': userId,
        'deptId': deptId
      }).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        if (this.form.postIds) {
          this.form.postSelect = this.form.postIds.split(',')
        }
        if (this.form.roleNames) {
          this.form.roleNames = this.form.roleNames.split(',')
        }
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['system:user:edit'])
      }).catch(() => {})
    },
    getDictData() {
      this.$dictGroup('sys_normal_disable').then(response => {
        this.optionOfStatus = response
      }).catch(e => {})
      this.$dictGroup('sys_user_sex').then(response => {
        this.optionOfGender = response
      }).catch(e => {})
      postSelectData().then(response => {
        this.optionOfPost = response.param.data
      }).catch(e => {})
    },
    changePost(value) {
      this.form.postIds = value.toString()
    },
    selectDept() {
      this.openDeptDialog = true
      const selected = this.form.deptId
      this.$nextTick(() => {
        this.$refs.deptDialog.init(selected)
      })
    },
    setDept(node) {
      this.form.deptId = node[0].id
      this.form.deptName = node[0].title
    },
    selectRole() {
      this.openRoleDialog = true
      const selected = this.form.roleIds
      this.$nextTick(() => {
        this.$refs.roleDialog.init(selected)
      })
    },
    setRole(nodes) {
      this.form.roleIds = nodes.map(node => node.id).join(',')
      this.form.roleNames = nodes.map(node => node.title)
    },
    onSubmit() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          userSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.$refs.userForm.resetFields()
            this.visible = false
          }).catch(() => {})
        }
      })
    },
    onClose() {
      this.form.roleNames = []
      this.$refs.userForm.resetFields()
      this.visible = false
    }
  }
}
</script>
